import Vue from 'vue'
import 'normalize.css/normalize.css'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import '@/styles/index.scss'
import App from './App'
import store from './store'
import router from './router'
import { constantRoutes } from '@/router'
import { buildRouter } from '@/utils'
import '@/icons'
import '@/permission'
import AjaxPlugin from './plugins/ajax'

import '../public/static/kindeditor/themes/default/default.css'
import VueKindEditor from './plugins/kindeditor.js'
Vue.use(VueKindEditor)

Vue.use(AjaxPlugin)
Vue.use(ElementUI, { size: 'small' })
Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    const info = window.localStorage.getItem('account')
    const menus = window.localStorage.getItem('menus')
    if (info) {
      store.commit('account', JSON.parse(info))
      if (!store.state.app.menus.length && menus) {
        const menusJson = JSON.parse(menus)
        const data = buildRouter(menusJson)
        const newRoutes = constantRoutes.concat(data)
        store.dispatch('app/setMenus', newRoutes)
        router.addRoutes(newRoutes)
        next(to.path)
      }
      next()
    } else {
      next('/login')
    }
  }
  next()
})

Vue.mixin({
  data () {
    return {
      account: store.state.account
    }
  },
  methods: {
    refreshWindow () {
      this.$store.commit('SET_ISROUTERVIEWSHOW', false)
      this.$nextTick(() => {
        this.$store.commit('SET_ISROUTERVIEWSHOW', true)
      })
    }
  }
})

Vue.directive('loaded-callback', {
  inserted: function (el, binding, vnode) {
    binding.value(el, binding, vnode)
  }
})

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
